<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/27
 * Time: 17:50
 */

namespace app\index\controller;


use app\service\TaskService;
use Redis\Redis;
use think\Db;

class EmployeeInfo extends Common
{

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 员工列表
     */
    function index()
    {
        # where 条件初始化
        $_where = "biz_id = " . $this->bizId;
        # 岗位筛选
        $job = input('post.jobs_info');
        if (!empty($job)) {
            $_where .= " and jobs_info = '" . $job . "'";
        }
        # 操作标识
        $mark = input('post.mark');
        # 员工状态筛选
        $status = input('post.status');
        if (!is_null($status)) {
            # 1=>试用期  2=>正式员工  0=>离职 3=》不包含离职的
            if ($status == 0 or ($status==3 and $mark=='Attendance') or ($status ==3 and !array_key_exists('sex',input()))) {
                $_where .= " and employee_status != 0";
            } else {
                if($status==3){
                    $status=0;
                }
                $_where .= " and employee_status = " . $status;
            }
        }
        # 获取门店类型
        $bizInfo = getsBizInfoArray($this->bizId);
        if ($mark == 'Attendance' and $bizInfo['biz_type'] != 3) {
            # 出勤员工查询
            $_where .= " and jobs_id > 5";
        }
        # 员工性别筛选
        $sex = input('post.sex');
        if (!empty($sex) or ($sex == 0 and $sex != null)) {
            # 1=>男  0=>女  2=>未知
            $_where .= " and employee_sex = " . $sex;
        }
        # 手机号搜索
        $searchInfo = input('post.searchInfo');
        if (!empty($searchInfo)) {
            $_where .= " and employee_phone like '%" . $searchInfo . "%'";
        }
//        $redis = new Redis();
//        $info = $redis->hGetJson('employeeList', strval($this->bizId));
//        if (empty($info)) {

        # 查询员工列表
        $info = Db::table('employee e')
            ->field('e.employee_name staff_name,e.id staff_id,jobs_info position,employee_head head_pic,employee_phone phone,
            (select group_concat(station_title) from station where team_id in (select distinct team_id from user_team_mapping where user_id=e.id)) work_list,
             case employee_status 
                  when 1 then "试用期"
                  when 2 then "已转正"
                  when 0 then "离职"
            end status')
            ->where($_where)
            ->where(array('del_status' => 1))
            ->select();
//            # 过期时间
//            $_expira = strtotime(date('Y-m-d 23:59:59')) - time();
//            $redis->hSetJson('employeeList', strval($this->bizId), $info, $_expira);
//        }
        return array('status' => true, 'data' => $info);
    }

    private $jobMark = '';
    private $noAttendance = [];

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 工单中修改服务人员时查询员工列表
     */
    function checkEmployee()
    {
        $redis = new Redis();
//        $redis->hDel('employeeList', strval($this->bizId));
        $info = $redis->hGetJson('employeeList', strval($this->bizId));
        if (empty($info)) {
            # 获取门店类型
            $bizType = Db::table('biz')->field('biz_type')->where(array('id' => $this->bizId))->value('biz_type');
            if ($bizType == 1) {
                $jobMark = "(select mark from jobs where id = jobs_id) mark,";
            } else {
                $jobMark = "'attendant' mark,";
            }
            # 查询员工列表
            $info = Db::table('employee e')
                ->field('e.employee_name staff_name,e.id staff_id,jobs_info position,' . $jobMark . 'employee_head head_pic,employee_phone phone,del_status,
             case employee_status 
                  when 1 then "试用期"
                  when 2 then "已转正"
                  when 0 then "离职"
            end status,employee_status')
                ->where(array('biz_id' => $this->bizId))
                ->select();
            # 过期时间
            $_expira = strtotime(date('Y-m-d 23:59:59')) - time();
            $redis->hSetJson('employeeList', strval($this->bizId), $info, $_expira);
        }
        # 接收员工类型
        $type = input('post.type');
        if ($type == 1) {
            $this->jobMark = 'attendant';
        }
        # 查询未出勤的员工
        $logAttendance = Db::table('log_attendance')->field('employee_id')
            ->where("date(create_time) = '" . date('Y-m-d') . "'")
            ->select();
        if (!empty($logAttendance)) {
            $this->noAttendance = array_column($logAttendance, 'employee_id');
        }
        # 根据类型来筛选员工(同时去掉已经离职的员工)
        $info = array_filter($info, function ($v) {
            if ($v['employee_status'] == 0) {
                # 过滤掉离职的员工
                return false;
            } else {
                if ($v['del_status'] == 2) {
                    return false;
                }
                if (!empty($this->jobMark) and $v['mark'] != $this->jobMark) {
                    # 根据员工类型来过滤
                    return false;
                }
// else {
                if (in_array($v['staff_id'], $this->noAttendance)) {
                    # 过滤掉未出勤的员工
                    return false;
                } else {
                    return $v;
                }
//                }
            }
        });
        return array('status' => true, 'data' => $info);
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 工单中修改员工信息
     */
    function modifyStaff()
    {
        # 接收订单编号
        $orderNumber = input('post.order_number');
        # 接收工单id
        $workOrderId = input('post.workOrder_id');
        # 接收选择的员工id集合
        $employeeId = input('post.employee_id');
        # 接收员工类型(1->服务人员  2->推荐人员)
        $employeeType = input('post.employee_type');
        # 接收工单类型(1->服务工单  2->商品工单)
        $orderType = input('post.order_type');
        if (!empty($workOrderId) and !empty($orderNumber)) {
            # 查询订单状态(订单已经完成的不可以修改员工)
            $orderStatus = Db::table('orders')->field('id')
                ->where(array('order_number' => $orderNumber))
                ->where("order_status != 5 and order_status != 7")
                ->find();
            if (!empty($orderStatus)) {
                # 要修改的数据
                if ($employeeType == 1) {
                    $_data = array("employee_id" => $employeeId);
                } else {
                    $_data = array("referrer" => $employeeId);
                }
                # 表
                if ($orderType == 1) {
                    $_table = 'order_server';
                } else {
                    $_table = 'order_biz';
                }
                # 修改数据
                Db::table($_table)->data($_data)->where(array('id' => $workOrderId))->update();
                return array('status' => true, 'msg' => '修改成功');
            } else {
                return array('status' => false, 'msg' => '该订单已完成,不可修改员工');
            }
        } else {
            return array('status' => false, 'msg' => '工单id/订单编号 为空');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询岗位信息
     */
    function jobInfo()
    {
        $info = Db::table('job')->field('id,jobs_title')->where(array('jobs_status' => 1))->select();
        return array('status' => true, 'msg' => '查询成功', 'info' => $info);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询员工信息
     */
    function employeeInfo()
    {
        $id = input('post.id');
        if (empty($id)) {
            return array('status' => false, 'msg' => '员工ID为空');
        }
        $info = Db::table('employee e')
            ->field("employee_create,employee_positive,wx_authority,satrap,
              employee_name,basic_salary,employee_age,employee_sex,employee_hugh,jobs_info,
              employee_idcard,employee_phone,employee_status,jobs_id,positive_salary,trial_full trial_full_salary,formal_full worker_full_salary")
            ->join('employee_mapping em', 'em.employee_id=e.id', 'left')
            ->where(array('e.id' => $id))
            ->find();
        $info['wx_authority'] = explode(',', $info['wx_authority']);
        return array('status' => true, 'info' => $info);
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content  修改员工信息
     */
    function writeInfo()
    {
        # 接收信息
        $info = input('post.');
        $id = $info['id'];
        unset($info['id']);
        unset($info['mark']);
        if (!empty($info) and !empty($id)) {
            # 判断身份证号和手机号是否重复
            $repeatInfo = Db::table('employee')->field('id,jobs_id')->where(array('employee_phone' => $info['employee_phone']))
                ->whereOr(array('employee_idcard' => $info['employee_idcard']))->find();
            if (!empty($repeatInfo) and $repeatInfo['id'] != $id) {
                return array('status' => false, 'msg' => '身份证号或手机号重复');
            }
            # 修改员工信息
            $_info = array(
                'employee_name' => $info['employee_name'],
                'employee_age' => $info['employee_age'],
                'employee_sex' => $info['employee_sex'],// 员工性别 1->男 2->女 0->未知
                'employee_idcard' => $info['employee_idcard'],
                'employee_phone' => $info['employee_phone'],
                'jobs_info' => $info['jobs_info'],
                'employee_create' => $info['employee_create'],// 入职时间
                'employee_hugh' => $info['employee_hugh'],  // 月休天数
                'employee_status' => $info['employee_status'],  //员工状态  1->试用期 2->已转正  0->离职
                'wx_authority' => implode(',', $info['wx_authority']),  // 员工权限  , 英文逗号拼接
//                'satrap' => $info['satrap'], // 是否为主管   0->不是  1->是
                'employee_code' => $info['employee_phone'],
            );
            # 查询岗位id
            $jobId = Db::table('jobs')->field('id')->where(array('jobs_title'=>$info['jobs_info']))->value('id');
            if(!empty($jobId) and $jobId != $repeatInfo['jobs_id']){
                $_info['jobs_id'] = $jobId;
            }
            $mappingInfo = array(
                'employee_positive' => $info['employee_positive'],// 转正时间
                'basic_salary' => $info['basic_salary'],//  试用期 基本工资
                'positive_salary' => $info['positive_salary'], // 转正后 基本工资
                'trial_full' => $info['trial_full_salary'],//试用期满勤工资
                'formal_full' => $info['worker_full_salary']//转正满勤工资
            );
            Db::table('employee')->where(array('id' => $id))->update($_info);
            $this->_Redis->hSet('employeeAuthority', $id, implode(',', $info['wx_authority']));
            Db::table('employee_mapping')->where(array('employee_id' => $id))->update($mappingInfo);
            $this->_Redis->hDel('employeeList', strval($this->bizId));
            return array('status' => true, 'msg' => '修改成功');
        } else {
            return array('status' => false, 'msg' => '修改信息存在空值');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 删除员工
     */
    function delEmployee()
    {
        # 接收员工id
        $employeeId = input('post.employee_id');
        if (empty($employeeId)) {
            return array('status' => false, 'msg' => '员工id不能为空');
        }
        Db::table('employee')->where(array('id' => $employeeId))->update(array('del_status' => 2));
        $this->_Redis->hDel('employeeList', strval($this->bizId));
        return array('status' => true, 'msg' => '删除成功');
    }

    /**
     * @access public
     * @content 员工考勤
     */
    function attendance()
    {
        # 接收员工id
        $employeeId = Input('post.employeeId');
        if (!empty($employeeId)) {
            # 将员工id字符串解析为数组,拼接成字符串
            if (!is_array($employeeId))
                $employee_id = explode(',', $employeeId);
            if (!empty($employee_id)) {
                $sqlArr = array();
                foreach ($employee_id as $k => $v) {
                    array_push($sqlArr, array('employee_id' => $v, 'create_time' => date('Y-m-d H:i:s')));
                }
                if (!empty($sql)) {
                    Db::table('log_attendance')->insertAll($sqlArr);
                }
            }
        }
        # 存入redis
        $this->_Redis->hSet('attendance' . $this->bizId, 'mark', '1', strtotime(date("Y-m-d 23:59:59")) - time());
        # 完成员工考勤任务
        TaskService::finishDayTask($this->bizId,4);
        return array('status' => true);
    }

    /**
     * @return array
     * @content 考勤状态
     */
    function attendance_status()
    {
//        $this->_Redis->hDel('attendance' . $this->bizId, 'mark');
        $mark = $this->_Redis->hGet('attendance' . $this->bizId, 'mark');
        if ($mark) {
            # 已经考勤过
            $mark = 1;
        } else {
            #  查询该门店下是否存在员工
            $employeeInfo = Db::table('employee')->where(array('biz_id'=>$this->bizId))->where("employee_status != 0")->count();
            if($employeeInfo > 0){
                $mark = 0;
            }else{
                $this->_Redis->hSet('attendance' . $this->bizId, 'mark', '1', strtotime(date("Y-m-d 23:59:59")) - time());
                $mark = 1;
            }
        }
        return array('status' => true, 'mark' => $mark);
    }
}
